<?php
namespace Framework\Cache;


class Store
{

	public $prefix;

	public $_igbinaryAvailable = false;

	public function __construct($config=[])
	{
		unset($config['driver']);
		\Framework\App::configure($this, $config);

		$this->prefix = isset($config['prefix']) ? $config['prefix'] : app('config')->get('cache.prefix') ;

		$this->init();
	}

	public function init(){}

    public function buildKey($key)
    {
        if (is_string($key)) {
            $key = ctype_alnum($key) && mb_strlen($key, '8bit') <= 32 ? $key : md5($key);
        } else {
            if ($this->_igbinaryAvailable) {
                $serializedKey = igbinary_serialize($key);
            } else {
                $serializedKey = serialize($key);
            }

            $key = md5($serializedKey);
        }

        return $this->prefix . $key;
    }

	public function get($key)
	{
		$key = $this->buildKey($key);
        $value = $this->getValue($key);

        return unserialize($value);
	}
	
	public function set($key, $value, $duration = 0)
	{
        $key = $this->buildKey($key);
        $value = serialize($value);

        return $this->setValue($key, $value, $duration);
	}

    public function delete($key)
    {
        $key = $this->buildKey($key);

        return $this->deleteValue($key);
    }
}